import React, { createRef, memo, useEffect, useState } from 'react'
import JKRequest from '@/services'

const Home = memo(() => {
  // 定义状态
  const [highScore, setHighScore] = useState({})

  // 网络请求，useEffect在dom加载完成后回调
  useEffect(() => {
    JKRequest.get({url:'/home/highscore'}).then(res => {
      console.log(res)
      // 把实时更新的数据传入设置setHighScore的方法中，这样highScore每次都是获取新数据
      setHighScore(res)
    })
  },[])
  const titleEl = createRef()
  function getRef(){
    console.log(titleEl.current);
    
  }
  console.log(highScore instanceof Object);

  return (
    <div>
      <h2 ref={titleEl} onClick={getRef}>{highScore.title}</h2>
      <h3>{highScore.subtitle}</h3>
      <ul>
        {
          // Uncaught TypeError: Cannot read properties of undefined (reading 'map')
          // 因为刚开始更新的时候highScore为空对象.list为undefined，所以没有map这个api
          // 使用?.来判断数据是否加载
          highScore?.list?.map((item) => {
            return (<li key={item.id}>{item.name}</li>)
          })
        }
      </ul>
    </div>
  )
})

export default Home